<template>
  <div class="chart-container">
    <div ref="chart" style="width: 100%; height: 400px"></div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { StatisticsApi } from '@/api/zszx/statistics'

const chart = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

// 获取数据并渲染图表
const fetchDataAndRender = async () => {
  try {
    const res = await StatisticsApi.annualStartEnd()
    console.log('res', res)

    const monthlyStartEnd = await StatisticsApi.monthlyStartEnd(2024)
    console.log('monthlyStartEnd', monthlyStartEnd)

    const { annualStartCount, annualEndCount, annualPaid } = res

    // 合并数据
    const yearMap = new Map()

    // 处理新增合同生效数量
    annualStartCount.forEach((item: any) => {
      const year = item.year
      if (!yearMap.has(year)) {
        yearMap.set(year, { year, startCount: 0, endCount: 0, paidAmount: 0 })
      }
      yearMap.get(year).startCount = item.num
    })

    // 处理到期合同数量
    annualEndCount.forEach((item: any) => {
      const year = item.year
      if (!yearMap.has(year)) {
        yearMap.set(year, { year, startCount: 0, endCount: 0, paidAmount: 0 })
      }
      yearMap.get(year).endCount = item.num
    })

    // 处理交费金额
    annualPaid.forEach((item: any) => {
      const year = item.declare_year
      if (!yearMap.has(year)) {
        yearMap.set(year, { year, startCount: 0, endCount: 0, paidAmount: 0 })
      }
      yearMap.get(year).paidAmount = item.num
    })

    // 转换为数组并按年份排序
    const data = Array.from(yearMap.values()).sort((a, b) => a.year - b.year)

    // 提取各数据系列
    const years = data.map((item) => item.year)
    const startCounts = data.map((item) => item.startCount)
    const endCounts = data.map((item) => item.endCount)
    const paidAmounts = data.map((item) => item.paidAmount)

    // 配置图表选项
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: ['新增合同生效数量', '到期合同数量', '交费金额']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: years
      },
      yAxis: [
        {
          type: 'value',
          name: '合同数量',
          position: 'left'
        },
        {
          type: 'value',
          name: '交费金额(元)',
          position: 'right',
          axisLabel: {
            formatter: function (value: number) {
              if (value >= 10000) {
                return (value / 10000).toFixed(1) + '万'
              }
              return value.toString()
            }
          }
        }
      ],
      series: [
        {
          name: '新增合同生效数量',
          type: 'line',
          data: startCounts,
          yAxisIndex: 0
        },
        {
          name: '到期合同数量',
          type: 'line',
          data: endCounts,
          yAxisIndex: 0
        },
        {
          name: '交费金额',
          type: 'line',
          data: paidAmounts,
          yAxisIndex: 1
        }
      ]
    }

    if (chartInstance) {
      chartInstance.setOption(option)
    }
  } catch (error) {
    console.error('获取年度统计数据失败:', error)
  }
}

onMounted(() => {
  if (chart.value) {
    chartInstance = echarts.init(chart.value)
    fetchDataAndRender()
    window.addEventListener('resize', () => chartInstance?.resize())
  }
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    window.removeEventListener('resize', () => chartInstance?.resize())
  }
})
</script>

<style scoped>
.chart-container {
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
</style>
